package com.hedl.classroom.controller;

import com.hedl.classroom.base.exception.OnlinecClassroomException;
import com.hedl.classroom.base.model.PageParams;
import com.hedl.classroom.base.model.PageResult;
import com.hedl.classroom.model.dto.QueryMediaParamsDto;
import com.hedl.classroom.model.dto.UploadFileParamsDto;
import com.hedl.classroom.model.dto.UploadFileResultDto;
import com.hedl.classroom.model.po.MediaFiles;
import com.hedl.classroom.service.MediaFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 媒资文件管理接口
 */
@Slf4j
@Api(value = "媒资文件管理接口",tags = "媒资文件管理接口")
@RestController
public class MediaFilesController {

    @Resource
    private MediaFileService mediaFileService;

    @ApiOperation("媒资列表查询接口")
    @PostMapping("/files")
    public PageResult<MediaFiles> list(PageParams pageParams, @RequestBody QueryMediaParamsDto queryMediaParamsDto){
        Long companyId = 1232141425L;
        return mediaFileService.queryMediaFiels(companyId,pageParams,queryMediaParamsDto);
    }

    @ApiOperation("上传图片")
    @RequestMapping(value = "/upload/coursefile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public UploadFileResultDto upload(@RequestPart("filedata")MultipartFile filedata,
                                      @RequestParam(value = "folder", required = false) String folder,
                                      @RequestParam(value = "objectName", required = false) String objectName) {
        UploadFileParamsDto uploadFileParamsDto = new UploadFileParamsDto();
        uploadFileParamsDto.setFileSize(filedata.getSize());
        uploadFileParamsDto.setFilename(filedata.getOriginalFilename());
        Long companyId = 1232141425L;

        String contentType = filedata.getContentType();
        if (contentType.contains("image")) {
            // 图片
            uploadFileParamsDto.setFileType("001001");
        } else {
            // 其他
            uploadFileParamsDto.setFileType("001003");
        }
        uploadFileParamsDto.setContentType(contentType);
        try {
/*
            try {
                TimeUnit.MINUTES.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

 */

            UploadFileResultDto uploadFileResultDto = mediaFileService.uploadFile(companyId, uploadFileParamsDto,
                    filedata.getBytes(), folder, objectName);
            return uploadFileResultDto;
        } catch (IOException e) {
            OnlinecClassroomException.cast("上传文件过程出错");
        }
        return null;
    }

}
